package xyz.syyrjx.provider.task;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.syyrjx.client.SyyrjxRpcClient;
import xyz.syyrjx.provider.conf.SyyrjxRpcProviderConfiguration;
import xyz.syyrjx.provider.util.SyyrjxRpcProviderHeartClientStartUtil;
import xyz.syyrjx.request.SyyrjxRpcRegistryRequest;
import xyz.syyrjx.util.SyyrjxRpcRandomUtil;

import java.util.*;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/14 - 21:03
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SyyrjxRpcProviderSchedule {

    private final static Logger LOGGER = LoggerFactory.getLogger(SyyrjxRpcProviderSchedule.class);

    private SyyrjxRpcClient client;

    public void run(SyyrjxRpcRegistryRequest request) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (client.getChannel() == null || !client.getChannel().isActive()) {
                    LOGGER.debug("重新连接");
                    client.setChannel(null);
                    try {
                        SyyrjxRpcProviderHeartClientStartUtil.start(client);
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage());
                    }
                } else {
                    LOGGER.debug("发送心跳");
                    client.send(request);
                }
            }
        };
        new Timer().schedule(task, 0L, SyyrjxRpcProviderConfiguration
                .getConfiguration().getHeartBeatInterval());
    }
}
